/*Purpose: Merge permid variable onto tradeline, public record, inquiry, collections, and summary files.  We merge from the header file and use teditseq.  */
  /*We do this because teditseq  is "messed up" (un-mergeable) on the rollup file, so in order to merge tradelines with rollup, we must use permid.*/

libname save "/data" ;   

/*header records*/
data head;
     set save.header2008_dec(keep=teditseq permid2004);
run;

proc sort data=head;
     by teditseq;
run;

/*trade records*/
proc sort data=save.trade2008_dec;
     by teditseq;
run;

/* merge by teditseq to get permid variable on trade file*/
/* number of unique teditseq on trade file before = number of unique teditseq and permid after merge, that means everyone has a permid, and it's a good merge*/
data save.trade2008_dec(rename=(permid2004=permid));
     merge head(in=in1) save.trade2008_dec(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*
proc sql;
select count(distinct teditseq) as UniqueTESQ,
       count(distinct permid) as Uniquepermid,
       count(*) as nobs
       from save.trade2008_dec;
quit;
run;
endsas;
*/

/*inquiry records*/
proc sort data=save.inquiry2008_dec;
     by teditseq;
run;

/* merge by teditseq to get permid variable on inquiry file*/
data save.inquiry2008_dec(rename=(permid2004=permid));
     merge head(in=in1) save.inquiry2008_dec(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*public records records*/
proc sort data= save.pubrec2008_dec;
     by teditseq;
run;

/* merge by teditseq to get permid variable on pubrec file*/
data save.pubrec2008_dec(rename=(permid2004=permid));
     merge head(in=in1) save.pubrec2008_dec(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*collections records*/
proc sort data= save.collect2008_dec;
     by teditseq;
run;

/* merge by teditseq to get permid variable on collections file*/
data save.collect2008_dec(rename=(permid2004=permid));
     merge head(in=in1) save.collect2008_dec(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*summary records*/
proc sort data= save.summary2008_dec;
     by teditseq;
run;


/* merge by teditseq to get permid variable on summary file*/
data save.summary2008_dec(rename=(permid2004=permid));
     merge head(in=in1) save.summary2008_dec(in=in2);
     by teditseq;
     if in1 and in2;
run;

proc contents data=save.summary2008_dec;
run;
